Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		signature: getApp().globalData.signature,
		token: getApp().globalData.token,
		nickName: getApp().globalData.nickName,
		desc: getApp().globalData.desc,
		openId: getApp().globalData.openId,
		avatarUrl: getApp().globalData.avatarUrl,
		activities: [],
		cursor: 0,
		isQuery: false,
		showDetails: false,
		selectActivty: null,
		users: [],
		msgs: [],
		followerCursor: 0,
		msgCursor: 0,
		isQueryFollowers: false,
		isQueryMsgs: false,
		isNoMore: false,
	},



	onClose() {
		this.setData({
			showDetails: false,
		})
	},

	jumpToUtils(e) {
		wx.showActionSheet({
			itemList: [
				"世界BK积分排名",
				"投票工具"
			],
			title: '工具箱',
			content: 'this is a feature!',
			success(res){
				let index = res.tapIndex
					switch (index) {
						case 0:
							wx.navigateTo({
								url: '/pages/box/ranking/rank',
							})
							break
							case 1:
								break
					}
			},
			complete(res){
				if (res.cancel) {

				}

				if (res.confirm) {
					
				}
			}
		})
	},

	//跳转到详情
	jumpToDetails(e) {
		this.setData({
			selectActivty: null,
			followerCursor: 0,
			msgCursor: 0,
			users: [],
			msgs: [],
		})
		const index = e.currentTarget.dataset.index
		// var obj = JSON.stringify(this.data.activities[index])
		// console.log("jumpToDetails: ",obj)
		// wx.navigateTo({
		// 	url: '/pages/todo/detail?obj=' + obj + '&token=' + this.data.token,
		// })
		this.setData({
			showDetails: true,
			selectActivty: this.data.activities[index],
		})

		this.getActivityFollowers()
	},

	//跳转新增活动界面
	jumpToAddActivity() {
		wx.navigateTo({
			url: '/pages/todo/add?token=' + this.data.token,
		})
	},


	/**
	 * 获取活动列表
	 * @param {用户请求token} token 
	 */
	queryActivities(token) {
		if (this.data.isQuery) return;
		this.setData({
			isQuery: true,
		})
		const dayjs = require('dayjs')
		console.log("查询列表 token = ", token)
		console.log("查询列表 cursor = ", this.data.cursor)
		wx.request({
			url: 'https://marklife.love/5h4h/get/activity',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				token: token,
				type: 0,
				limit: 10,
				cursor: this.data.cursor,
			},
			complete: () => {
				this.setData({
					isQuery: false
				})
			},
			success: (res) => {
				var errCode = res.data.err
				console.log("查询", res.data)
				if (errCode == 1000) {
					//查询活动列表成功
					console.log("查询成功")
					getApp().globalData.needReRefresh = false
					for (let index = 0; index < res.data.data.length; index++) {
						var ct = res.data.data[index].create_time;
						var desc = res.data.data[index].desc
						res.data.data[index].create_time = dayjs(ct).format('YYYY-MM-DD HH:mm');
						desc = desc.replace(/\\n/g, '\n');
						res.data.data[index].desc = desc
						if (res.data.data[index].st == null || res.data.data[index].st == "null") {
							res.data.data[index].st = null
						}
					}
					if (res.data.data.length == 0) {
						this.setData({
							isNoMore: true,
						})
						// wx.showModal({
						// 	title: '加载完毕',
						// 	content: '没有更多了',
						// 	showCancel: false,
						// 	complete: (res) => {
						// 		if (res.cancel) {

						// 		}

						// 		if (res.confirm) {

						// 		}
						// 	}
						// })
					}
					if (this.data.cursor == 0) {
						this.setData({
							activities: res.data.data,
							cursor: res.data.cursor
						})
					} else {
						var temp = [...this.data.activities, ...res.data.data]
						this.setData({
							activities: [...this.data.activities, ...res.data.data],
							cursor: res.data.cursor
						})
					}

					wx.stopPullDownRefresh()
					wx.hideLoading()
				} else {
					wx.stopPullDownRefresh()
					wx.hideLoading()
					//查询活动列表失败 未知原因
					wx.showModal({
						title: '查询失败',
						content: '抱歉，查询失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				wx.stopPullDownRefresh()
				wx.hideLoading()
				wx.showModal({
					title: '查询失败',
					content: '抱歉，查询失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},


	/**
	 * 关注活动
	 */
	attendActivity() {
		console.log("查询关注列表 token = ", this.data.token)
		wx.request({
			url: 'https://marklife.love/5h4h/attend/activity',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				token: this.data.token,
				activity: this.data.selectActivty.key,
				add: true,
			},
			success: (res) => {
				console.log("attend activity: ", res.data)
				var errCode = res.data.err
				if (errCode == 1000) {
					wx.hideLoading()
					//新增成功
					//新增成功提示
					wx.showModal({
						title: '恭喜您',
						icon: "success",
						content: '参加活动成功',
						showCancel: false,
						complete: (res) => {
							if (res.confirm) {
								this.subscribeMessage()
								this.setData({
									cursor: 0,
								})
								this.getActivityFollowers()
							}
						}
					})
				} else {
					//新增失败 未知原因
					wx.hideLoading()
					wx.showModal({
						title: '关注活动失败',
						content: '抱歉，关注活动失败，我也没时间去排查错误原因：' + errCode,
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			}
		})
	},


	//申请授权
	subscribeMessage() {
		wx.requestSubscribeMessage({
			tmplIds: ['yxrr1WvLBJdHD1un8jsGC8sdiEiWG9vyHa1jRqhlMsI'], //这里填入我们生成的模板id
			success(res) {
				console.log('授权成功', res)
			},
			fail(res) {
				console.log('授权失败', res)
			}
		})
	},

	/**
	 * 获取关注活动用户列表
	 */
	getActivityMsgs() {
		if (this.data.isQueryMsgs) return;
		this.setData({
			isQueryMsgs: true,
		})
		console.log("查询留言板 token = ", this.data.token)
		wx.request({
			url: 'https://marklife.love/5h4h/get/activity/msg',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				token: this.data.token,
				activity: this.data.selectActivty.key,
				limit: 20,
				cursor: this.data.msgCursor,
			},
			complete: () => {
				this.setData({
					isQueryMsgs: false
				})
			},
			success: (res) => {
				var errCode = res.data.err
				if (errCode == 1000) {
					//查询留言板列表成功
					console.log("查询留言板成功", res.data.data)

					if (res.data.data.length == 0) {}

					if (this.data.msgCursor == 0) {
						this.setData({
							msgs: res.data.data,
							msgCursor: res.data.cursor
						})
					} else {
						var temp = [...this.data.msgs, ...res.data.data]
						this.setData({
							msgs: [...this.data.msgs, ...res.data.data],
							msgCursor: res.data.cursor
						})
					}

					wx.stopPullDownRefresh()
					wx.hideLoading()
				} else {
					wx.stopPullDownRefresh()
					wx.hideLoading()
					//查询留言板失败 未知原因
					// wx.showModal({
					// 	title: '查询失败',
					// 	content: '抱歉，查询失败，我也没时间去排查错误原因',
					// 	showCancel: false,
					// 	complete: (res) => {
					// 		if (res.cancel) {}
					// 		if (res.confirm) {}
					// 	}
					// })
				}
			},
			fail: (res) => {
				wx.stopPullDownRefresh()
				wx.hideLoading()
				wx.showModal({
					title: '查询失败',
					content: '抱歉，查询失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	/**
	 * 获取关注活动用户列表
	 */
	getActivityFollowers() {
		if (this.data.isQueryFollowers) return;
		this.setData({
			isQueryFollowers: true,
			followerCursor: 0,
		})
		console.log("查询关注列表 token = ", this.data.token)
		console.log("查询关注列表 cursor = ", this.data.followerCursor)
		wx.request({
			url: 'https://marklife.love/5h4h/get/activity/followers',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				token: this.data.token,
				activity: this.data.selectActivty.key,
				limit: 20,
				cursor: this.data.followerCursor,
			},
			complete: () => {
				this.setData({
					isQueryFollowers: false
				})
			},
			success: (res) => {
				var errCode = res.data.err
				if (errCode == 1000) {
					//查询关注活动用户列表成功
					console.log("查询成功", res.data.data)
					if (res.data.data.length == 0) {}
					if (this.data.followerCursor == 0) {
						this.setData({
							users: res.data.data,
							followerCursor: res.data.cursor
						})
					} else {
						var temp = [...this.data.users, ...res.data.data]
						this.setData({
							users: [...this.data.users, ...res.data.data],
							followerCursor: res.data.cursor
						})
					}

					wx.stopPullDownRefresh()
					wx.hideLoading()
				} else {
					wx.stopPullDownRefresh()
					wx.hideLoading()
					//查询活动列表失败 未知原因
					wx.showModal({
						title: '查询失败',
						content: '抱歉，查询失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				wx.stopPullDownRefresh()
				wx.hideLoading()
				wx.showModal({
					title: '查询失败',
					content: '抱歉，查询失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		let key = options.key
		console.log("select activity key: ", key)
		getApp().globalData.shareKey = key

		wx.showToast({
			title: getApp().globalData.shareKey,
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		console.log("onShow 1")
		this.setData({
			signature: getApp().globalData.signature,
			token: getApp().globalData.token,
			nickName: getApp().globalData.nickName,
			desc: getApp().globalData.desc,
			openId: getApp().globalData.openId,
			avatarUrl: getApp().globalData.avatarUrl,
		})
		console.log("onShow 2")
		if (this.data.signature == null) {
			getApp().showNoLoginDialog()
			return
		}
		console.log("onShow 3")
		if (this.data.token == null) {
			this.checkLogin()
			console.log("onShow 5")
			console.log("-------------------------")
			this.checkNeedParseShareInfo()
			return
		}

		console.log("onShow 4")
		if (getApp().globalData.needReRefresh) {
			wx.startPullDownRefresh()
		}

		console.log("onShow 5")
		console.log("-------------------------")
		this.checkNeedParseShareInfo()
	},

	/**
	 * 检查是否有需要显示的分享key
	 */
	checkNeedParseShareInfo() {

		let shareKey = getApp().globalData.shareKey
		console.log("checkNeedParseShareInfo key= " + shareKey)
		if (shareKey != null && shareKey.length > 0) {
			wx.showLoading({
				title: '请稍等...',
			})
			wx.request({
				url: 'https://marklife.love/5h4h/get/activity/info',
				method: 'POST',
				//传参使用form-data格式
				header: {
					'content-type': 'application/x-www-form-urlencoded' //修改此处即可
				},
				data: {
					key: shareKey,
				},
				complete: () => {
					wx.hideLoading()
				},
				success: (res) => {
					var errCode = res.data.err
					if (errCode == 1000) {
						//查询关注活动用户列表成功
						console.log("获取信息成功", res.data.data)
						if (res.data.data.st == null || res.data.data.st == "null") {
							res.data.data.st = null
						}
						this.setData({
							selectActivty: res.data.data,
							showDetails: true,
						})
						getApp().globalData.shareKey = null

						this.getActivityFollowers()
						wx.hideLoading()
					} else {
						wx.hideLoading()
						//查询活动列表失败 未知原因
						wx.showModal({
							title: '获取信息失败',
							content: '抱歉，获取信息失败，我也没时间去排查错误原因',
							showCancel: false,
							complete: (res) => {
								if (res.cancel) {}
								if (res.confirm) {}
							}
						})
					}
				},
				fail: (res) => {
					wx.hideLoading()
					wx.showModal({
						title: '获取信息失败',
						content: '抱歉，获取信息失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			})
		}
	},

	/**
	 * 检查登陆状态
	 * @param signature wx id 凭证
	 */
	checkLogin() {
		console.log("checkLogin: signature= ", this.data.signature)
		wx.request({
			url: 'https://marklife.love/mark/v1/login',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				account: this.data.signature,
				password: 'wx_password_' + this.data.signature,
			},
			success: (res) => {
				console.log("checkLogin", res.data)
				var errCode = res.data.err
				var token = res.data.token
				if (errCode == 1000) {
					wx.hideLoading()
					//登陆成功
					//保存用户的登陆token
					let wxInfo = res.data.data.wx_info
					this.setData({
						token: token,
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
						openId: wxInfo.wx_open_id,
						signature: wxInfo.wx_signature,
					})
					getApp().globalData.token = token
					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.openId = wxInfo.wx_open_id
					getApp().globalData.signature = wxInfo.wx_signature
					wx.startPullDownRefresh();
					// wx.setStorageSync('token', token)
				} else {
					getApp().showNoLoginDialog()
				}
			}
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {
		//如果是下拉刷新，那么就要把指针回到0
		this.setData({
			cursor: 0,
			isNoMore: false,
		})
		if (this.data.token != null) {
			this.queryActivities(this.data.token, 0)
		}
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {
		if (this.data.isNoMore) return
		wx.showLoading({
			title: '正在加载',
		})
		this.queryActivities(this.data.token, this.data.m_cursor)
	},



	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {
		let activity = this.data.selectActivty;
		var randomImg = "/imgs/share/share_bboy1.png";
		return {
			title: activity.name,
			desc: activity.desc,
			path: 'pages/todo/todo?key=' + activity.key,
			imageUrl: randomImg, // 可以更换分享的图片
			success: function (res) {
				// 转发成功
				wx.showToast({
					title: '分享成功',
					icon: "none"
				});
			},
			fail: function (res) {
				// 转发失败
				wx.showToast({
					title: '分享失败',
					icon: "none"
				})
			}
		}
	},

	//通知所有的关注者
	pushAllFollowers() {

		let curAct = this.data.selectActivty
		let key = curAct.key

		console.log("url " + ('https://marklife.love/5h4h/push/activity?activity=' + key))
		console.log("curAct " + curAct.name)
		console.log("curAct.name= " + curAct.name)
		console.log("curAct.location.name= " + ((curAct.location.name == null || curAct.location.name == "") ? "地点未定" : curAct.location.name))
		console.log("date= " + (curAct.st == null ? "时间未定" : curAct.st))
		console.log("user_name= " + curAct.user.wx_info.wx_name)
		console.log("token= " + this.data.token)

		wx.request({
			url: 'https://marklife.love/5h4h/push/activity?activity=' + key,
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				name: curAct.name,
				location_name: (curAct.location.name == null || curAct.location.name == "") ? " " : curAct.location.name,
				date: curAct.st == null ? " " : curAct.st,
				st: " ",
				user_name: curAct.user.wx_info.wx_name,
				token: this.data.token,
			},
			success: (res) => {
				console.log("checkLogin", res.data)
				var errCode = res.data.err
				var token = res.data.token
				if (errCode == 1000) {
					wx.showModal({
						title: '恭喜你',
						content: '完成活动通知！',
						showCancel: false,
						complete: (res) => {
							if (res.confirm) {

							}
						}
					})

				} else {
					wx.showModal({
						title: '很抱歉',
						content: '活动通知失败。',
						showCancel: false,
						complete: (res) => {
							if (res.confirm) {

							}
						}
					})
				}
			}
		})
	},
	
	jumpFailed(){
	
	}
})

